2017-03-19 61 views
0

我已经使用POST请求将数据发送到MYSQL数据库。我使用POST请求提出了以下代码。所以,只是想先问问如果这个代码可以运行好或不好如何在不使用Json的情况下在android中执行HTTP POST请求

如果有人可以告诉m具体是什么setRequestProperty(“Key”,“Value”)方法,我会非常感谢那个人这个KEY和VALUE是什么意思。

我也在清单文件中提供了Internet权限。

请尽快回复。

try { 
     URL url = new URL("http://192.168.221.105/hanish/datainsert.php"); 
     HttpURLConnection client = (HttpURLConnection) url.openConnection(); 


     client.setRequestMethod("POST"); 
     client.setRequestProperty(“id”,”l”); 
     client.setDoOutput(true); 

     OutputStream outputPost = new BufferedOutputStream(client.getOutputStream()); 
     writeStream(outputPost); 

    } catch (MalformedURLException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

} 

private void writeStream(OutputStream outputPost) throws IOException { 
    String v= l; 
    outputPost.write(v.getBytes()); 
    outputPost.flush(); 
} 
+0

'如果此代码运行良好或不'。试试看,我会说。不要喊。 – greenapps

回答

0

为此,您应该运行异步任务。但是,我建议使用AsyncHttpClient库。它为您处理异步请求。

要使用这个库,你应该添加使用摇篮buildscript行家依赖于格式:

dependencies { 
    compile 'com.loopj.android:android-async-http:1.4.9' 
    } 

然后,导入HTTP包:

import com.loopj.android.http.*; 

然后写下面的代码:

AsyncHttpClient asyncHttpClient = new AsyncHttpClient(); 
RequestParams requestParams = new RequestParams(); 
requestParams.add("id", "1"); 
asyncHttpClient.post("http://192.168.221.105/hanish/datainsert.php", requestParams, new AsyncHttpResponseHandler() { 
    @Override 
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { 
     String response = new String(responseBody); // this is your response string 
    } 

    @Override 
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { 
     // Here you write code if there's error 
    } 
}); 

我希望这会有所帮助。

相关问题