在这里,我们将给大家分享关于HttpUrlConnection如何设置SO_KEEPALIVE的知识,让您更了解家字取名男孩名字的本质,同时也会涉及到如何更有效地Android中使用HttpURLCo
在这里,我们将给大家分享关于HttpUrlConnection如何设置SO_KEEPALIVE的知识,让您更了解家字取名男孩名字的本质,同时也会涉及到如何更有效地Android 中使用 HttpURLConnection 和 HttpClient 发送 Http 请求、Android-HttpUrlConnection没有关闭。最终导致SocketException、Android-HttpUrlConnection没有关闭最终导致SocketException、cURL和HttpURLConnection-发布JSON数据的内容。
本文目录一览:- HttpUrlConnection如何设置SO_KEEPALIVE(家字取名男孩名字)
- Android 中使用 HttpURLConnection 和 HttpClient 发送 Http 请求
- Android-HttpUrlConnection没有关闭。最终导致SocketException
- Android-HttpUrlConnection没有关闭最终导致SocketException
- cURL和HttpURLConnection-发布JSON数据
HttpUrlConnection如何设置SO_KEEPALIVE(家字取名男孩名字)
是否可以为JDK stdlib设置套接字级别选项(如SO_KEEPALIVE)HttpUrlConnection?我试图找出一种获取HTTP请求的方法,该方法不会成为偶尔的“挂起”连接(似乎经常由于网络数据包丢失而发生)的受害者。一个更强大的HTTP客户端。我知道有这种setReadTimeout方法,但我正在尝试寻找一些方法来使TCP流恢复正常运行,而不是像读取超时那样中止它。或者至少报告连接发生故障,而不是永久挂起读取。但这还允许读取在假设连接“仍处于活动状态”的情况下“在需要时”返回。
经过一些检查,看来C层套接字和Java层套接字的SO_KEEPALIVE缺省值均为“ off”。
答案1
小编典典这不是基于一个谬论,而是基于三个谬论。
尽管名称不正确,SO_KEEPALIVE不会“将TCP流推回生活”。在两个小时的默认间隔后,它仅检测到死连接。不是您要找的东西。
读取超时不会终止连接。它抛出一个
SocketTimeoutException
。连接仍然有效,后续读取可能会成功。检测到丢弃的数据包并在TCP中重新传输。
使用读取超时。
Android 中使用 HttpURLConnection 和 HttpClient 发送 Http 请求
在 android 应用程序中,可以使用 HttpURLConnection 发送 HTTP 请求。详见如下实例
1、activity_main.xml 布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送请求"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</ScrollView>
</LinearLayout>
2、MainActivity.java
package com.example.testhttp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener{
private Button sendRequest;
private TextView content;
private static final int SHOW_RESPONSE_CONTENT = 0;
private Handler handler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE_CONTENT:
String response = (String) msg.obj;
//显示到界面上
content.setText(response);
break;
default:
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取发送按钮
sendRequest = (Button) findViewById(R.id.send_request);
//获取TextView
content = (TextView) findViewById(R.id.content);
sendRequest.setOnClickListener(this);
}
//重写点击方法
@Override
public void onClick(View view) {
if(view.getId() == R.id.send_request){
//如果是点击发送按钮,则处理Http请求--使用HttpURLConnection
sendRequestWithHttpURLConnection();
}
}
/**
* 使用HttpURLConnection发送请求
*/
public void sendRequestWithHttpURLConnection(){
//新起一线程
new Thread(new Runnable() {
//处理逻辑
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
//设置参数
//发送请求
connection.setRequestMethod("GET");
//连接超时时间
connection.setConnectTimeout(5000);
InputStream in = connection.getInputStream();
//对服务器返回的输入流进行读取
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine())!=null){
builder.append(line);
}
//使用Message
Message message = new Message();
message.what = SHOW_RESPONSE_CONTENT;
message.obj = builder.toString();
handler.sendMessage(message);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(connection!=null){
//断开连接
connection.disconnect();
}
}
}
}).start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
3、获取网络访问权限
修改 AndroidManifest.xml,添加:
<uses-permission android:name="android.permission.INTERNET"/>
4、结果
点击发送按钮,如下所示:
这就是服务器返回给我吗的 Html 代码。
如果是发送数据给服务器呢?看如下代码:
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=yy&password=admin");
此外,可以使用 HttpClient 发送 Http 请求,
其他不变,在 MainActivity.java 类中添加方法 sendRequestWithHttpClient,如下:
private void sendRequestWithHttpClient(){
new Thread(new Runnable() {
@Override
public void run() {
try {
HttpClient httpClient= new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.baidu.com");
HttpResponse httpResponse = httpClient.execute(httpGet);
if(httpResponse.getStatusLine().getStatusCode() == 200){
//请求和相应成功
HttpEntity entity = httpResponse.getEntity();
//防止中文乱码
String responseText = EntityUtils.toString(entity,"utf-8");
Message message = new Message();
message.what = SHOW_RESPONSE_CONTENT;
message.obj = responseText.toString();
handler.sendMessage(message);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
修改 onClick 方法,如下:
//重写点击方法
@Override
public void onClick(View view) {
if(view.getId() == R.id.send_request){
//如果是点击发送按钮,则处理Http请求--使用HttpURLConnection
// sendRequestWithHttpURLConnection();
//如果是点击发送按钮,则处理Http请求--使用HttpClient
sendRequestWithHttpClient();
}
}
效果如下:
Android-HttpUrlConnection没有关闭。最终导致SocketException
我在运行Jellybean(4.1-4.3)的设备中遇到HttpUrlConnection的一些问题,其中连接未关闭,并且执行多次后导致SocketException“打开的文件过多”。
我确实调用了HttpUrlConnection.disconnect()并在finally块中关闭了所有Inputstream,Outputstream,Reader和Writers。
转到adb shell并执行a将netstat
显示该应用程序创建的所有连接均处于CLOSE_WAIT状态。
InputStream inputStream = httpUrlConnection.getInputStream();// After calling inputStream.read() then the problem occurs. I think the // inputstream doesn''t get closed even after calling close in a finally block. // The InputStream is a ChunkedInputStream if that helps.
我尝试了在2.3.3、4.0.3和4.4上运行的其他设备,但没有遇到此问题。
还有另一种方法可以手动关闭连接吗?
答案1
小编典典我终于找到了解决方法。似乎软糖在“保持活动”连接上有问题。我刚刚将Connection =
Close添加到我的请求标头中,现在一切正常。在执行netstat时,我看到连接现在正在关闭,并且由于“打开的文件太多”,我不再得到SocketException。
Android-HttpUrlConnection没有关闭最终导致SocketException
我在运行Jellybean(4.1-4.3)的设备中遇到HttpUrlConnection的一些问题,其中连接未关闭,并且执行多次后导致SocketException“打开的文件过多”。
我确实调用了HttpUrlConnection.disconnect()并在finally块中关闭了所有Inputstream,Outputstream,Reader和Writers。
转到adb shell并执行a将netstat
显示该应用程序创建的所有连接均处于CLOSE_WAIT状态。
InputStream inputStream = httpUrlConnection.getInputStream();
// After calling inputStream.read() then the problem occurs. I think the
// inputstream doesn't get closed even after calling close in a finally block.
// The InputStream is a ChunkedInputStream if that helps.
我尝试了在2.3.3、4.0.3和4.4上运行的其他设备,但没有遇到此问题。
还有另一种方法可以手动关闭连接吗?
cURL和HttpURLConnection-发布JSON数据
如何使用HttpURLConnection发布JSON数据?我正在尝试:
HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));httpcon.setDoOutput(true);httpcon.setRequestProperty("Content-Type", "application/json");httpcon.setRequestProperty("Accept", "application/json");httpcon.setRequestMethod("POST");httpcon.connect();StringReader reader = new StringReader("{''value'': 7.5}");OutputStream os = httpcon.getOutputStream();char[] buffer = new char[4096];int bytes_read; while((bytes_read = reader.read(buffer)) != -1) { os.write(buffer, 0, bytes_read);// I am getting compilation error here}os.close();
我在第14行中收到编译错误。
cURL请求为:
curl -H "Accept: application/json" \-H "Content-Type: application/json" \-d "{''value'': 7.5}" \"a URL"
这是处理cURL请求的方法吗?任何信息对我都会非常有帮助。
谢谢。
答案1
小编典典OutputStream希望使用字节,并且您要向其传递字符。试试这个:
HttpURLConnection httpcon = (HttpURLConnection) ((new URL("a url").openConnection()));httpcon.setDoOutput(true);httpcon.setRequestProperty("Content-Type", "application/json");httpcon.setRequestProperty("Accept", "application/json");httpcon.setRequestMethod("POST");httpcon.connect();byte[] outputBytes = "{''value'': 7.5}".getBytes("UTF-8");OutputStream os = httpcon.getOutputStream();os.write(outputBytes);os.close();
今天关于HttpUrlConnection如何设置SO_KEEPALIVE和家字取名男孩名字的讲解已经结束,谢谢您的阅读,如果想了解更多关于Android 中使用 HttpURLConnection 和 HttpClient 发送 Http 请求、Android-HttpUrlConnection没有关闭。最终导致SocketException、Android-HttpUrlConnection没有关闭最终导致SocketException、cURL和HttpURLConnection-发布JSON数据的相关知识,请在本站搜索。
本文标签: