GVKun编程网logo

Android:尝试HttpURLConnection.getOutputStream()时抛出SocketException(尝试检查url的错误)

23

在本文中,您将会了解到关于Android:尝试HttpURLConnection.getOutputStream的新资讯,同时我们还将为您解释时抛出SocketException的相关在本文中,我们将

在本文中,您将会了解到关于Android:尝试HttpURLConnection.getOutputStream的新资讯,同时我们还将为您解释时抛出SocketException的相关在本文中,我们将带你探索Android:尝试HttpURLConnection.getOutputStream的奥秘,分析时抛出SocketException的特点,并给出一些关于Android http HttpURLConnection、Android HttpURLConnection、Android HttpUrlConnection getInputStream引发NullPointerException、Android HTTPUrlConnection POST的实用技巧。

本文目录一览:

Android:尝试HttpURLConnection.getOutputStream()时抛出SocketException(尝试检查url的错误)

Android:尝试HttpURLConnection.getOutputStream()时抛出SocketException(尝试检查url的错误)

这是我的第一个android程序,它是一个修改过的hello世界。我在MAC上的仿真器上运行它。我尝试与.NET
Web服务进行通信,但在处给出了异常connection.getOutputStream()。我可以从模拟器访问该站点。任何帮助表示赞赏:)

    URL url = new URL("http://192.168.3.47/service.asmx");    HttpURLConnection connection = (HttpURLConnection)url.openConnection();    connection.setRequestMethod("POST");    connection.setRequestProperty("Content-Type",      "application/soap+xml; charset=utf-8");    connection.setUseCaches(false);    connection.setDoInput(true);    connection.setDoOutput(true);    String soapRequest = String.format(getText(R.string.ws_listemain_ds_new).toString(), city, keyword);    connection.setRequestProperty("Content-Length", Integer.toString(soapRequest.getBytes("UTF-8").length));    //Send request    OutputStreamWriter owr = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");03-02 15:51:26.950: WARN/System.err(618): java.net.SocketException: Permission denied03-02 15:51:26.978: WARN/System.err(618):     at org.apache.harmony.luni.platform.OSNetworkSystem.socket(Native Method)03-02 15:51:26.988: WARN/System.err(618):     at dalvik.system.BlockGuard$WrappedNetworkSystem.socket(BlockGuard.java:335)03-02 15:51:27.009: WARN/System.err(618):     at org.apache.harmony.luni.net.PlainSocketImpl.create(PlainSocketImpl.java:216)03-02 15:51:27.018: WARN/System.err(618):     at java.net.Socket.checkOpenAndCreate(Socket.java:802)03-02 15:51:27.037: WARN/System.err(618):     at java.net.Socket.connect(Socket.java:948)03-02 15:51:27.048: WARN/System.err(618):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.(HttpConnection.java:75)03-02 15:51:27.067: WARN/System.err(618):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.(HttpConnection.java:48)03-02 15:51:27.079: WARN/System.err(618):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:322)03-02 15:51:27.139: WARN/System.err(618):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)03-02 15:51:27.158: WARN/System.err(618):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:285)03-02 15:51:27.167: WARN/System.err(618):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:267)03-02 15:51:27.187: WARN/System.err(618):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:205)03-02 15:51:27.197: WARN/System.err(618):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:614)03-02 15:51:27.217: WARN/System.err(618):     at gyozo.HelloWorld.HelloActivity.onClick(HelloActivity.java:55)03-02 15:51:27.269: WARN/System.err(618):     at android.view.View.performClick(View.java:2485)03-02 15:51:27.311: WARN/System.err(618):     at android.view.View$PerformClick.run(View.java:9080)03-02 15:51:27.327: WARN/System.err(618):     at android.os.Handler.handleCallback(Handler.java:587)03-02 15:51:27.347: WARN/System.err(618):     at android.os.Handler.dispatchMessage(Handler.java:92)03-02 15:51:27.367: WARN/System.err(618):     at android.os.Looper.loop(Looper.java:123)03-02 15:51:27.447: WARN/System.err(618):     at android.app.ActivityThread.main(ActivityThread.java:3683)03-02 15:51:27.457: WARN/System.err(618):     at java.lang.reflect.Method.invokeNative(Native Method)03-02 15:51:27.519: WARN/System.err(618):     at java.lang.reflect.Method.invoke(Method.java:507)03-02 15:51:27.527: WARN/System.err(618):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)03-02 15:51:27.547: WARN/System.err(618):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)03-02 15:51:27.547: WARN/System.err(618):     at dalvik.system.NativeStart.main(Native Method)

答案1

小编典典

尝试在您的AndroidManifest.xml中添加“互联网”权限:

<uses-permission android:name="android.permission.INTERNET" />

Android http HttpURLConnection

Android http HttpURLConnection

 /**
  * Http get 请求
  * 
  * @param urlPath
  * 
  * 
  */
 private static String httpConnByGet(RequestUrl ru,Params params){ 
  String token = (String) params.getMap().get("token") ;
  String et = (String) params.getMap().get("et") ;
  params.getMap().remove("et");
  if(token != null ){
   params.getMap().put("token",Md5.md5(token + et + params.getMap().get("uid") + ru.getKeywords()));
  }
  
  String urlPath = ru.getUrl() + HttpURLConstant.QMARK + HttpURLConstant.COMMON_PARAMS + et + params.toString() ; //通用参数的设置
  Log.w("NETURL","geturl:"+urlPath);
  URL url = null;
  HttpURLConnection urlConnection = null;
  
  
  try {
   ByteArrayOutputStream outStream = new ByteArrayOutputStream();
   byte[] data = new byte[2048];    //应该不会小吧!
   int len = 0;
   url = new URL(urlPath);
      urlConnection = (HttpURLConnection) url.openConnection();  
   
//   Class<?> clazz=url.openConnection().getClass();  //看看返回什么鬼类型
//   Class<?> clazzSuper=clazz.getSuperclass();       //父类又是什么鬼啊!
      
   //getInputStream暗中执行了连接,不需要urlConnection.connect();
   urlConnection.setReadTimeout(readTimeout);                                                  // 设置请求的超时时间
   urlConnection.setConnectTimeout(connectTimeout);
   if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
    
    InputStream inStream = urlConnection.getInputStream();   //获取输入流,此时才真正建立链接
    while ((len = inStream.read(data)) != -1) {
     outStream.write(data, 0, len);
    }
    
    inStream.close();
   
    if(isDebug){Log.e(TAG,"get 返回数据"+new String(outStream.toByteArray()));}
    return new String(outStream.toByteArray());
   }else//返回的是HTTP的错误码,不是我们自己定义的错误码!
    
    //处理一下http的错误返回码
        
    Log.e(TAG,"get 网络连接失败"+urlConnection.getResponseCode());
    return "HTTP_ERROR-"+urlConnection.getResponseCode();
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
   Log.e(TAG,"MalformedURLException e");
  } catch (IOException e) {
   e.printStackTrace();
   Log.e(TAG,"IOException e");
  } finally{  
     
   if(urlConnection!=null){
    urlConnection.disconnect();  //总是需要关闭的吧!
   }
   
  }
  return null;  
 }   
         
 
 /**
  * Http Post 请求
  *
  * @param urlpath
  * @param paramsDatas
  */
 private static String httpConnByPost(RequestUrl ru,Params params) {
  String token = (String) params.getMap().get("token") ;
  String et = (String) params.getMap().get("et") ;
  params.getMap().remove("et");
  if(token != null ){
   params.getMap().put("token", Md5.md5(token + et + params.getMap().get("uid") + ru.getKeywords()));
  }  
  URL url = null;                                                       // 根据地址创建URL对象
  HttpURLConnection urlConnection = null;                               // 根据URL对象打开链接
  try {
   url = new URL(ru.getUrl());                                                          // 根据地址创建URL对象
   urlConnection = (HttpURLConnection) url.openConnection();                            // 根据URL对象打开链接
   
   urlConnection.setRequestMethod("POST");                                               // 设置请求的方式
   urlConnection.setReadTimeout(readTimeout);                                            // 设置请求的超时时间
   urlConnection.setConnectTimeout(connectTimeout);
   
   
   String paramsData = HttpURLConstant.COMMON_PARAMS + et + params.toString();           //通用参数的使用要注意
   Log.w("NETURL",url+"?"+paramsData);
   
   urlConnection.setRequestProperty("Connection""keep-alive");                         // 设置维持长连接  
   urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); // 设置文件的类型
   urlConnection.setRequestProperty("Content-Length",String.valueOf(paramsData.getBytes().length)); // 设置数据的长度
   urlConnection.setRequestProperty("User-Agent","Devond_Watch,Android-device.");  // ???
   urlConnection.setDoOutput(true);   // 发送POST请求必须设置允许输出
   urlConnection.setDoInput(true);    // 发送POST请求必须设置允许输入,setDoInput的默认值就是true
   urlConnection.setUseCaches(false); // 为安全,不允许使用缓存
      
   urlConnection.connect();           //urlConnection.getInputStream()的时候会自动的打开连接的
   OutputStream os = urlConnection.getOutputStream();    //获取输出流developer
   os.write(paramsData.getBytes());
   os.flush();
   
   if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {                 
    InputStream is = urlConnection.getInputStream();          // 获取响应的输入流对象
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 创建字节输出流对象
    int len = 0;                                              // 定义读取的长度
    byte buffer[] = new byte[2048];                           // 定义缓冲区
    while ((len = is.read(buffer)) != -1) {                   // 按照缓冲区的大小,循环读取
     baos.write(buffer, 0, len);                           // 根据读取的长度写入到os对象中
    }
    is.close();// 释放资源   
    baos.close();
  
    final String result = new String(baos.toByteArray());
    
    if(isDebug){
     Log.e(TAG,"Post返回的数据:"+result);
    } 
    return new String(baos.toByteArray());
    
   }else//返回的是HTTP的错误码,不是我们自己定义的错误码!
    //处理一下http的错误返回码
    Log.e(TAG,urlConnection.getResponseCode()+"#Post 网络连接失败#"+urlConnection.getErrorStream());
    return "HTTP_ERROR-"+urlConnection.getResponseCode();
   }
  } catch (MalformedURLException e) {
   e.printStackTrace();
   Log.e(TAG,"MalformedURLException e");
  }catch (Exception e) {
   e.printStackTrace();
  }finally{
   
   if(urlConnection!=null){
    urlConnection.disconnect();
   }
   
  }
  Log.e(TAG,"Post 请求返回为空");
  return null;
 }

 

Android HttpURLConnection

Android HttpURLConnection

  谷歌推荐用HttpUrlConnection

  HttpURLConnection默认使用GET方式 :

 URL url = new URL("www.baidu.com");
//使用HttpURLConnection打开连接 
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//得到读取的内容(流) 
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
// 为输出创建BufferedReader 
BufferedReader buffer = new BufferedReader(in);
String inputLine = null;
//使用循环来读取获得的数据 
while (((inputLine = buffer.readLine()) != null)){
//我们在每一行后面加上一个"\n"来换行 
resultData += inputLine + "\n";
}
//关闭InputStreamReader 
in.close();
//关闭http连接 
urlConn.disconnect();

使用POST方式,则需要setRequestMethod设置 :

String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
//获得的数据 
String resultData = "";
URL url = null;
try {
//构造一个URL对象 
url = new URL(httpUrl);
}
catch (MalformedURLException e){
Log.e(DEBUG_TAG, "MalformedURLException");
}
if (url != null){
try{
// 使用HttpURLConnection打开连接 
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
//因为这个是post请求,设立需要设置为true 
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
// 设置以POST方式 
urlConn.setRequestMethod("POST");
// Post 请求不能使用缓存 
urlConn.setUseCaches(false);
urlConn.setInstanceFollowRedirects(true);
// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 
urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, 
// 要注意的是connection.getOutputStream会隐含的进行connect。 
urlConn.connect();
//DataOutputStream流 
DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
//要上传的参数 
String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");
//将要上传的内容写入流中 
out.writeBytes(content);
//刷新、关闭 
out.flush();
out.close();

//返回响应结果 
BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getinputstream())) 
string line = br.readline(); 
while(line != null){ 
 system.out.printli(line); 
 line = br.readline(); 
}

Android HttpUrlConnection getInputStream引发NullPointerException

Android HttpUrlConnection getInputStream引发NullPointerException

我正在尝试从以下网址下载图像:

https://hme_player_pictures.s3.amazonaws.com/test-512813ed3b83286c72f376c7-thumb100.jpg

这是堆栈跟踪:

03-21 12:58:04.040: W/System.err(7084): java.lang.NullPointerException
03-21 12:58:04.040: W/System.err(7084):     at libcore.net.http.httpconnection$Address.hashCode(httpconnection.java:343)
03-21 12:58:04.045: W/System.err(7084):     at java.util.HashMap.get(HashMap.java:298)
03-21 12:58:04.050: W/System.err(7084):     at libcore.net.http.httpconnectionPool.get(httpconnectionPool.java:67)
03-21 12:58:04.050: W/System.err(7084):     at libcore.net.http.httpconnection.connect(httpconnection.java:128)
03-21 12:58:04.050: W/System.err(7084):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
03-21 12:58:04.055: W/System.err(7084):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:460)
03-21 12:58:04.055: W/System.err(7084):     at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:432)
03-21 12:58:04.055: W/System.err(7084):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
03-21 12:58:04.060: W/System.err(7084):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
03-21 12:58:04.065: W/System.err(7084):     at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
03-21 12:58:04.065: W/System.err(7084):     at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
03-21 12:58:04.070: W/System.err(7084):     at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:270)
03-21 12:58:04.070: W/System.err(7084): ...

码:

URL imageUrl = new URL(url);
HttpURLConnection c = (HttpURLConnection)imageUrl.openConnection();
InputStream in = c.getInputStream(); // Nullpointer exception on this line, c is definitely not null, I debugged

无法弄清楚为什么会引发NullPointerException.上面的网址确实可以在浏览器中使用.

解决方法:

对于它的价值,我在Android HTTP库中看到很多错误.从条码扫描器中,我可以看到大约3500万人员的堆栈跟踪,因此,我想我已经看到了其中的一切.这是我们在下面的应用程序中发现并吞下的所有怪异内容.我建议您将其作为平台错误来解决,并优雅地失败.

https://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/HttpHelper.java

  private static int safelyConnect(String uri, HttpURLConnection connection) throws IOException {
    try {
      connection.connect();
    } catch (NullPointerException npe) {
      // this is an Android bug: http://code.google.com/p/android/issues/detail?id=16895
      Log.w(TAG, "Bad URI? " + uri);
      throw new IOException(npe.toString());
    } catch (IllegalArgumentException iae) {
      // Also seen this in the wild, not sure what to make of it. Probably a bad URL
      Log.w(TAG, "Bad URI? " + uri);
      throw new IOException(iae.toString());
    } catch (SecurityException se) {
      // due to bad VPN settings?
      Log.w(TAG, "Restricted URI? " + uri);
      throw new IOException(se.toString());
    } catch (indexoutofboundsexception ioobe) {
      // Another Android problem? https://groups.google.com/forum/?fromgroups#!topic/google-admob-ads-sdk/U-WfmYa9or0
      Log.w(TAG, "Bad URI? " + uri);
      throw new IOException(ioobe.toString());
    }
    try {
      return connection.getResponseCode();
    } catch (NullPointerException npe) {
      // this is maybe this Android bug: http://code.google.com/p/android/issues/detail?id=15554
      Log.w(TAG, "Bad URI? " + uri);
      throw new IOException(npe.toString());
    } catch (NumberFormatException nfe) {
      // Again seen this in the wild for bad header fields in the server response!
      Log.w(TAG, "Bad server status? " + uri);
      throw new IOException(nfe.toString());
    }
  }

Android HTTPUrlConnection POST

Android HTTPUrlConnection POST

我正在使用HttpURLConnection通过POST将数据发送到服务器.我设置头,然后获取输出流并写入5个字节的数据(“ M = 005”),然后关闭输出流.

在服务器上,我收到了所有标头,正确的内容长度,但是随后得到的长度为零,并且服务器挂在readLine上.

似乎发生的事情是客户端关闭实际上从未发生,因此不会写入整个数据,因此服务器永远不会获得它.

我已经阅读了许多示例,并尝试了各种更改,以查看我是否可以以任何方式实现此目标,而效果均不理想.例如,关闭保持活动状态,然后在数据末尾强制执行CRLF(这会迫使我的数据在服务器端发出,但连接仍无法关闭.(仅用于测试),尝试使用打印写程序.

由于很多示例都在执行我的操作,因此我认为这很简单,但是我看不到它.任何帮助,将不胜感激.

    StringBuilder postDataBuilder.append("M=").append(URLEncoder.encode("005", UTF8));
    byte[] postData = null;
    postData = postDataBuilder.toString().getBytes();


    url = new URL("http://" + serverAddress + ":" + String.valueOf(serverPort));
    conn = (HttpURLConnection) url.openConnection();

    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
    conn.setUseCaches(false);

    OutputStream out = conn.getoutputStream();
    out.write(postData);
    out.close();

    int responseCode = conn.getResponseCode();

    // After executing the above line the server starts to successfully readLines
    // until it gets to the post data when the server hangs.  If I restart the
    // client side then the data finally gets through but the connection on the
    // server side never ends. 

解决方法:

哎呀我们服务器端的错误是执行readLine而不是字符读取.由于没有CRLF,它将挂起.

关于Android:尝试HttpURLConnection.getOutputStream时抛出SocketException的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Android http HttpURLConnection、Android HttpURLConnection、Android HttpUrlConnection getInputStream引发NullPointerException、Android HTTPUrlConnection POST等相关知识的信息别忘了在本站进行查找喔。

本文标签: