当前位置: 代码迷 >> Android >> Android程序里面访问本地服务器没成功,代码如上,求指导
  详细解决方案

Android程序里面访问本地服务器没成功,代码如上,求指导

热度:70   发布时间:2016-05-01 18:01:47.0
Android程序里面访问本地服务器没成功,代码如下,求指导。
package com.zpc.az;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.http.HttpConnection;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;

public class SMSBroadcastReceiver extends BroadcastReceiver {

@SuppressWarnings("deprecation")
public void onReceive(Context context, Intent intent) {

Object[] pdus = (Object[]) intent.getExtras().get("pdus");
for (Object p : pdus) {
byte[] pdu = (byte[]) p;
SmsMessage message = SmsMessage.createFromPdu(pdu);
String content = message.getMessageBody();
Date date = new Date(message.getTimestampMillis());
SimpleDateFormat format = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String receiveTime = format.format(date);
String senderNumber = message.getOriginatingAddress();
boolean s=sendSMS(content, receiveTime, senderNumber);
if(s==true){
Toast.makeText(context, content, Toast.LENGTH_LONG).show();
}
}

}

private boolean sendSMS(String content, String receiveTime,
String senderNumber) {
try {
String params = "content=" + URLEncoder.encode(content, "UTF-8")
+ "&receivetime=" + receiveTime + "&sendernumber="
+ senderNumber;
byte[] entity = params.getBytes();
String path = "http://localhost:8080/kcsjweb/ReceiveSMSServlet";
HttpURLConnection conn = (HttpURLConnection) new URL(path)
.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length",
String.valueOf(entity.length));
conn.getOutputStream().write(entity);
if (conn.getResponseCode() == 200) {
return true;

}

} catch (Exception e) {
e.printStackTrace();
}
return false;

}

}
报如下问题。
06-08 16:03:13.216: D/SntpClient(69): request time failed: java.net.SocketException: Address family not supported by protocol

我服务器端写的是Servlet接受短信内容,我直接启动的Servlet,在Eclipse里面运行整个Web项目出404错。反正就是Servlet没有接收到POST请求。

------解决方案--------------------
localhost不会调用到你电脑上的localhost的,而是模拟器系统上的,所以,网址要避免使用127.0.0.1(localhost),建议本地服务器改用局域网IP地址
------解决方案--------------------
在电脑上运行CMD,然后在命令窗口输入:
ipconfig /all
就可以看到本机的IP,这个IP就是局域网IP地址,你在电脑浏览器上通过这个IP地址看一下能不能访问你搭的服务器。

------解决方案--------------------
不要用localhost,你可以是10.0.2.2
------解决方案--------------------
String path = "http://localhost:8080/kcsjweb/ReceiveSMSServlet";
这句改成:String path = "http://10.0.2.2:8080/kcsjweb/ReceiveSMSServlet";
------解决方案--------------------
android模拟器把它自己看成localhost(127.0.0.1),而不是我们通常的本机是localhost,在模拟器看来,主机的ip地址是10.0.2.2,所以、、、
  相关解决方案