我试图通过android studio上的Android应用程序连接到服务器,但我使用下面的代码遇到了一些麻烦:
链接是:
static final String SERVICE_API_URL = "http://192.168.90.74/android/user.php";
public class AccessServiceAPI {
/**
* Call service api with GET method and then return result form service as json string
* @param url
* @return
*/
public String getJSONStringFromUrl_GET(String url) {
JSONArray jsonArray = null;
HttpURLConnection httpURLConnection = null;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String line;
String jsonString = "";
try {
URL u = new URL(url);
httpURLConnection = (HttpURLConnection) u.openConnection();
httpURLConnection.setRequestMethod("GET");
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + '\n');
}
jsonString = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpURLConnection.disconnect();
}
return jsonString;
}
/**
* Convert json string to json object
* @param jsonString
* @return
*/
public JSONObject convertJSONString2Obj(String jsonString) {
JSONObject jObj = null;
try {
Log.w("convertJSONString2Obj", "JsonString=" + jsonString);
jObj = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
return jObj;
}
/**
* Get json string from URL with method POST
* @param serviceUrl
* @param params post data
* @return json string
*/
public String getJSONStringWithParam_POST(String serviceUrl, Map<String, String> params)
throws IOException
{
JSONArray jsonArray = null;
String jsonString = null;
HttpURLConnection conn = null;
String line;
URL url;
try
{
url = new URL(serviceUrl);
}
catch (MalformedURLException e)
{
throw new IllegalArgumentException("invalid url: " + serviceUrl);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext())
{
Map.Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.w("getJSONStringWithParam", "param=>" + body);
byte[] bytes = body.getBytes();
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
Log.w("getJSONStringWithParam", "Response Status = " + status);
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line + '\n');
}
jsonString = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return jsonString;
}
public String getJSONStringWithParam_POST(String serviceUrl,String params)
throws IOException
{
JSONArray jsonArray = null;
String jsonString = null;
HttpURLConnection conn = null;
String line;
URL url;
try
{
url = new URL(serviceUrl);
}
catch (MalformedURLException e)
{
throw new IllegalArgumentException("invalid url: " + serviceUrl);
}
Log.w("getJSONStringWithParam", "param=>" + params);
byte[] bytes = params.getBytes();
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
//conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Type", "application/json");
conn.connect();
// post the request
OutputStream out = conn.getOutputStream();
out.write (bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
Log.w("getJSONStringWithParam", "Response Status = " + status);
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null)
{
stringBuilder.append(line + '\n');
}
jsonString = stringBuilder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return jsonString;
}
}
,错误如下:
W/getJSONStringWithParam: param=>username=u&password=0000&action=login
I/System: core_booster, getBoosterConfig = false
W/System.err: java.net.ConnectException: failed to connect to /192.168.90.74 (port 80): connect failed: ENETUNREACH (Network is unreachable)
注意:我想提一下这个相同的代码以前工作过,一旦我重新启动我的电脑,它再也没有用了!
先谢谢你了!