項目中遇到傳json數(shù)據(jù)的接口,總結(jié)一下吧逝撬。再遇到就能更快的進行測試了东帅。后續(xù)集成到自動化測試接口軟件中。
json相關(guān)jar包下載
請求相關(guān)jar包下載
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
public abstract class TestSend {
// String URL = "url";
public static void main(String[] args) {
JSONObject jsobj1 = new JSONObject();
jsobj1.put("key","value");
//System.out.println(jsobj1);
post(jsobj1,"url");//注冊
}
public static String post(JSONObject json,String URL) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);
post.setHeader("Content-Type", "application/json");
post.addHeader("Authorization", "Basic YWRtaW46");
String result = "";
try {
StringEntity s = new StringEntity(json.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
post.setEntity(s);
// 發(fā)送請求
HttpResponse httpResponse = client.execute(post);
// 獲取響應(yīng)輸入流
InputStream inStream = httpResponse.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
inStream, "utf-8"));
StringBuilder strber = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
strber.append(line + "\n");
inStream.close();
result = strber.toString();
System.out.println(result);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
System.out.println("請求服務(wù)器成功球拦,做相應(yīng)處理");
} else {
System.out.println("請求服務(wù)端失敗");
}
} catch (Exception e) {
System.out.println("請求異常");
throw new RuntimeException(e);
}
return result;
}
}
積極迎接各種挑戰(zhàn),才會使自己更加強大。