PHP, JavaScript 및 기타 많은 스크립팅 언어에 경험이 있지만 Java 또는 Android에 대한 경험이 많지 않습니다.
POST 데이터를 PHP 스크립트 로 보내고 결과를 표시 하는 방법을 찾고 있습니다.
답변
* Android 6.0 이상에서 작동하는 업데이트 된 답변입니다. 의견에 대한 @Rohit Suthar , @Tamis Bolvari 및 @sudhiskr 에게 감사드립니다 . *
public class CallAPI extends AsyncTask<String, String, String> {
public CallAPI(){
//set context variables if required
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
String urlString = params[0]; // URL to call
String data = params[1]; //data to post
OutputStream out = null;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();
urlConnection.connect();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
참고 문헌 :
- https://developer.android.com/reference/java/net/HttpURLConnection.html
- NameValuePair를 사용하여 POST를 사용하여 HttpURLConnection에 매개 변수를 추가하는 방법
이전 답변
참고 :이 솔루션은 구식입니다. 5.1 이하의 Android 기기에서만 작동합니다. Android 6.0 이상에는이 답변에 사용 된 Apache http 클라이언트가 포함되어 있지 않습니다.
Apache Commons의 Http Client가 갈 길입니다. 이미 안드로이드에 포함되어 있습니다. 다음은이를 사용하여 HTTP Post를 수행하는 간단한 예입니다.
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
답변
대한 안드로이드 => 5
org.apache.http의 클래스와 AndroidHttpClient의 클래스는 한 되지 않습니다 에 안드로이드 5.1 . 이 클래스는 더 이상 유지 관리되지 않으므로 이러한 API를 사용하는 앱 코드 는 가능한 빨리 URLConnection 클래스로 마이그레이션해야 합니다.
https://developer.android.com/about/versions/android-5.1.html#http
HttpUrlConnection을 사용하여 코드를 공유 할 생각
public String performPostCall(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
…
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
또한 당신은 방법 을 게시 할 수 있습니다 :
conn.setRequestMethod("POST");
21/02/2016 업데이트
json 을 사용한 게시 요청 은 다음 예제를 참조하십시오.
public class Empty extends
AsyncTask<Void, Void, Boolean> {
String urlString = "http://www.yoursite.com/";
private final String TAG = "post json example";
private Context context;
private int advertisementId;
public Empty(Context contex, int advertisementId) {
this.context = contex;
this.advertisementId = advertisementId;
}
@Override
protected void onPreExecute() {
Log.e(TAG, "1 - RequestVoteTask is about to start...");
}
@Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
String response = "";
Log.e(TAG, "2 - pre Request to response...");
try {
response = performPostCall(urlString, new HashMap<String, String>() {
private static final long serialVersionUID = 1L;
{
put("Accept", "application/json");
put("Content-Type", "application/json");
}
});
Log.e(TAG, "3 - give Response...");
Log.e(TAG, "4 " + response.toString());
} catch (Exception e) {
// displayLoding(false);
Log.e(TAG, "Error ...");
}
Log.e(TAG, "5 - after Response...");
if (!response.equalsIgnoreCase("")) {
try {
Log.e(TAG, "6 - response !empty...");
//
JSONObject jRoot = new JSONObject(response);
JSONObject d = jRoot.getJSONObject("d");
int ResultType = d.getInt("ResultType");
Log.e("ResultType", ResultType + "");
if (ResultType == 1) {
status = true;
}
} catch (JSONException e) {
// displayLoding(false);
// e.printStackTrace();
Log.e(TAG, "Error " + e.getMessage());
} finally {
}
} else {
Log.e(TAG, "6 - response is empty...");
status = false;
}
return status;
}
@Override
protected void onPostExecute(Boolean result) {
//
Log.e(TAG, "7 - onPostExecute ...");
if (result) {
Log.e(TAG, "8 - Update UI ...");
// setUpdateUI(adv);
} else {
Log.e(TAG, "8 - Finish ...");
// displayLoding(false);
// finish();
}
}
public String performPostCall(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(context.getResources().getInteger(
R.integer.maximum_timeout_to_server));
conn.setConnectTimeout(context.getResources().getInteger(
R.integer.maximum_timeout_to_server));
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
Log.e(TAG, "11 - url : " + requestURL);
/*
* JSON
*/
JSONObject root = new JSONObject();
//
String token = Static.getPrefsToken(context);
root.put("securityInfo", Static.getSecurityInfo(context));
root.put("advertisementId", advertisementId);
Log.e(TAG, "12 - root : " + root.toString());
String str = root.toString();
byte[] outputBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write(outputBytes);
int responseCode = conn.getResponseCode();
Log.e(TAG, "13 - responseCode : " + responseCode);
if (responseCode == HttpsURLConnection.HTTP_OK) {
Log.e(TAG, "14 - HTTP_OK");
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
Log.e(TAG, "14 - False - HTTP_OK");
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
2016 년 8 월 24 일 업데이트
다음과 같은 최고의 라이브러리를 사용하십시오.
때문에 :
- HttpUrlConnection 및 HttpClient를 피하십시오
낮은 API 수준 (주로 Gingerbread 및 Froyo)에서 HttpUrlConnection 및 HttpClient는 완벽하지 않습니다.
- 그리고 AsyncTask도 피하십시오
- 그들은 훨씬 빠릅니다
- 그들은 모든 것을 캐시
Honeycomb (API 11)이 도입 된 이후 메인 스레드와 다른 별도의 스레드에서 네트워크 작업을 수행해야했습니다.
답변
이런 식으로 우리는 http post 메소드로 데이터를 보내고 결과를 얻을 수 있습니다
public class MyHttpPostProjectActivity extends Activity implements OnClickListener {
private EditText usernameEditText;
private EditText passwordEditText;
private Button sendPostReqButton;
private Button clearButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
usernameEditText = (EditText) findViewById(R.id.login_username_editText);
passwordEditText = (EditText) findViewById(R.id.login_password_editText);
sendPostReqButton = (Button) findViewById(R.id.login_sendPostReq_button);
sendPostReqButton.setOnClickListener(this);
clearButton = (Button) findViewById(R.id.login_clear_button);
clearButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.login_clear_button){
usernameEditText.setText("");
passwordEditText.setText("");
passwordEditText.setCursorVisible(false);
passwordEditText.setFocusable(false);
usernameEditText.setCursorVisible(true);
passwordEditText.setFocusable(true);
}else if(v.getId() == R.id.login_sendPostReq_button){
String givenUsername = usernameEditText.getEditableText().toString();
String givenPassword = passwordEditText.getEditableText().toString();
System.out.println("Given username :" + givenUsername + " Given password :" + givenPassword);
sendPostRequest(givenUsername, givenPassword);
}
}
private void sendPostRequest(String givenUsername, String givenPassword) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);
HttpClient httpClient = new DefaultHttpClient();
// In a POST request, we don't pass the values in the URL.
//Therefore we use only the web page URL as the parameter of the HttpPost argument
HttpPost httpPost = new HttpPost("http://www.nirmana.lk/hec/android/postLogin.php");
// Because we are not passing values over the URL, we should have a mechanism to pass the values that can be
//uniquely separate by the other end.
//To achieve that we use BasicNameValuePair
//Things we need to pass with the POST request
BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("paramUsername", paramUsername);
BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("paramPassword", paramPassword);
// We add the content that we want to pass with the POST request to as name-value pairs
//Now we put those sending details to an ArrayList with type safe of NameValuePair
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePAir);
try {
// UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs.
//This is typically useful while sending an HTTP POST request.
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
// setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
httpPost.setEntity(urlEncodedFormEntity);
try {
// HttpResponse is an interface just like HttpPost.
//Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the JAVA API, InputStream constructor do nothing.
//So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals("working")){
Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(givenUsername, givenPassword);
}
}
답변
다음은 외부 Apache 라이브러리를 사용하지 않고 멀티 파트 데이터를 POST하는 방법의 예입니다.
byte[] buffer = getBuffer();
if(buffer.length > 0) {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "RQdzAAihJq7Xp1kjraqf";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
// Send parameter #1
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"param1\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain; charset=US-ASCII" + lineEnd);
dos.writeBytes("Content-Transfer-Encoding: 8bit" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(myStringData + lineEnd);
// Send parameter #2
//dos.writeBytes(twoHyphens + boundary + lineEnd);
//dos.writeBytes("Content-Disposition: form-data; name=\"param2\"" + lineEnd + lineEnd);
//dos.writeBytes("foo2" + lineEnd);
// Send a binary file
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"param3\";filename=\"test_file.dat\"" + lineEnd);
dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dos.writeBytes(lineEnd);
dos.write(buffer);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
ByteArrayInputStream content = new ByteArrayInputStream(baos.toByteArray());
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(content);
HttpPost httpPost = new HttpPost(myURL);
httpPost.addHeader("Connection", "Keep-Alive");
httpPost.addHeader("Content-Type", "multipart/form-data; boundary="+boundary);
//MultipartEntity entity = new MultipartEntity();
//entity.addPart("param3", new ByteArrayBody(buffer, "test_file.dat"));
//entity.addPart("param1", new StringBody(myStringData));
httpPost.setEntity(entity);
/*
String httpData = "";
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
entity.writeTo(baos1);
httpData = baos1.toString("UTF-8");
*/
/*
Header[] hdrs = httpPost.getAllHeaders();
for(Header hdr: hdrs) {
httpData += hdr.getName() + " | " + hdr.getValue() + " |_| ";
}
*/
//Log.e(TAG, "httpPost data: " + httpData);
response = httpClient.execute(httpPost);
}
답변
@primpop 답변에 응답을 문자열로 변환하는 방법을 추가합니다.
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
}
답변
이미 Apache에 포함되어있는 Apache Commons HttpClient를 사용하는 것이 좋습니다.
일반적인 API 정보 는
Android 개발자 : Apache HTTP 클라이언트 패키지 요약 을 확인하십시오.
답변
이를 사용하여 HTTP POST 요청을 URL로 보낼 수 있습니다. 요청을 쉽게 보내고 응답을받을 수 있습니다. 나는 항상 이것을 사용합니다. 나는 나에게 잘 일한다.
///////////////////// Check SubScription ////////////////////
try {
AsyncHttpClient client = new AsyncHttpClient();
// Http Request Params Object
RequestParams params = new RequestParams();
String u = "B2mGaME";
String au = "gamewrapperB2M";
// String mob = "880xxxxxxxxxx";
params.put("usr", u.toString());
params.put("aut", au.toString());
params.put("uph", MobileNo.toString());
// params.put("uph", mob.toString());
client.post("http://196.6.13.01:88/ws/game_wrapper_reg_check.php", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
playStatus = response;
//////Get your Response/////
Log.i(getClass().getSimpleName(), "Response SP Status. " + playStatus);
}
@Override
public void onFailure(Throwable throwable) {
super.onFailure(throwable);
}
});
} catch (Exception e) {
e.printStackTrace();
}
또한 libs folde에 다음과 같은 Jar 파일을 추가해야합니다.
android-async-http-1.3.1.jar
마지막으로 build.gradle을 편집하십시오.
dependencies {
compile files('libs/<android-async-http-1.3.1.jar>')
}
마지막으로 프로젝트를 다시 빌드하십시오.