HttpURLConnection 收发报文

前段时间公司要接入华为的计费sdk,根据华为的文档,需要发送一个请求报文给华为,这里整理一下怎么用HttpURLConnection发送报文

要发送报文。

先贴代码

data.path是发送的目的地址

setDoOutPut是可以让url可以连接输出流

setUseCaches是否使用缓存(还没有尝试设置为true有什么影响,希望知道的人告诉我)

setRequestProperty就是设置请求的报头了

接下来得到Connect的OutPutStream

创建一个 OutPutStreamWriter

之后就是写入报文体了,应该还有其他方法吧

返回结果从connection.getInputStream中读出来

的实例URL url = new URL(data.path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);

connection.setRequestProperty("Content-Type",data.content_type);
connection.setRequestProperty("Accept",data.accept);
connection.setRequestProperty("Request-Id",data.requestID);
connection.setRequestProperty("Authorization",data.authorization);
connection.setRequestProperty("X-WSSE",data.X_WSSE);
connection.setRequestProperty("Body-Sign",data.Body_Sign);
connection.setRequestProperty("User-Agent",data.User_Agent);
connection.setRequestProperty("Host",data.Host);
OutputStream os = connection.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(data.Body);
bw.flush();
bw.close();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
StringBuilder result = new StringBuilder();
while((line=br.readLine())!=null)
{
    result.append(line);
}
br.close();
connection.disconnect();
Log.e("Hentai",result.toString());

 
  


你可能感兴趣的:(android)