httpURLConnection 请求发起post请求
常见请求头,在post请求之 前先了解一下,请求相关的基础
关于post 请求的方式比get 多了很多配置,其实大致一样,本想将get示例和post写在一起,这个博客功能有时有问题 一直在灰色的编辑框中跳不出去,只能另起一篇博客。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | private void doPost(String s) { try { // URl构建的是一上地址对象 URL url = new URL(UrlAddress); // 创建一个连接 HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection(); // 由于是post 请求需要配置参数 httpURLConnection.setDoInput( true ); httpURLConnection.setDoOutput( true ); // 配置请求头 httpURLConnection.setRequestMethod( "POST" ); // 配置请求是否有缓存 httpURLConnection.setDefaultUseCaches( false ); HttpURLConnection.setDefaultRequestProperty( "Accept-Charset" , "UTF-8" ); HttpURLConnection.setDefaultRequestProperty( "Content-Type" , "application/x-www-form-urlencoded" ); // 配置好了尝试连接准备 httpURLConnection.connect(); DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream()); // 拼接请求参数,比如条件,性别, String content = "set=" +s; outputStream.write(content.getBytes()); outputStream.flush(); outputStream.close(); //以下的处理和get 一样了 if (httpURLConnection.getResponseCode() == 200){ InputStream is =httpURLConnection.getInputStream(); BufferedReader br = new BufferedReader( new InputStreamReader( is )); StringBuffer Sbuffer = new StringBuffer(); String readLine = "" ; while ((readLine = br.readLine())!= null ){ Sbuffer.append(readLine); } is .close(); br.close(); httpURLConnection.disconnect(); Log.d( "Text" ,Sbuffer.toString()); } } catch (MalformedURLException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { } } //dopost 方法方法结束 |
用 HttpPost 封装好的组件的话比较直接,但是以下方法需要在另一线程调用,
private void doPost(String s) {
HttpPost httpPost = new HttpPost(urlAddress + method);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("sex", s));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
String result = EntityUtils.toString(httpResponse.getEntity());
Log.d("test", result);
} else {
Log.d("test","failed");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端