网上用java编写测接口的文章很多,但是在把代码复制过来运行后,发现都有这样那样的问题。以下是最新整理出来的
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.IIOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class FirstRealTest {public static void main(String[] args)throws IOException{
// TODO Auto-generated method stub// 创建默认的httpClient实例.
HttpClient httpclient = new DefaultHttpClient();
// 创建httppost
HttpPost httppost = new HttpPost("你要测的请求");
// 创建参数队列
// Listformparams = new ArrayList();
Listformparams = new ArrayList();
formparams.add(new BasicNameValuePair("mobile", "13225811329"));
formparams.add(new BasicNameValuePair("passwd", "ab123456"));
formparams.add(new BasicNameValuePair("from", "web"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity =new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
HttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
}
} finally {
((PrintStream) response).close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
((PrintStream) httpclient).close();
}
}