백엔드 개발 PHP 튜토리얼 Android PHP는 HttpClient를 사용하여 POST 요청을 제출하고 JSON을 사용하여 응답을 구문 분석합니다.

Android PHP는 HttpClient를 사용하여 POST 요청을 제출하고 JSON을 사용하여 응답을 구문 분석합니다.

Jul 29, 2016 am 09:12 AM
android import quot string

다음은 Android 프로그램에 네트워킹 기능을 추가하는 방법을 소개합니다. 물론, 먼저 서버가 있어야 합니다. 테스트만 한다면 대신 LAN(컴퓨터 Wi-Fi에 연결된 휴대폰)을 사용할 수 있습니다.

컴퓨터가 Apache+PHP 환경으로 구성되어 있어야 합니다.

다음은 간단한 Android 프로그램입니다. 특정 Java 기반만 있으면 그 의미를 대략적으로 "추측"할 수 있다고 생각합니다. (프로그램이 잘 작성되지 않을 수 있습니다)

안드로이드 프로그램

레이아웃 파일

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/<strong>Activity</strong>_vertical_margin"
    android:paddingLeft="@dimen/<strong>Activity</strong>_horizontal_margin"
    android:paddingRight="@dimen/<strong>Activity</strong>_horizontal_margin"
    android:paddingTop="@dimen/<strong>Activity</strong>_vertical_margin"
    tools:c
    android:orientation="vertical" >

    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:<strong>gravity</strong>="center"
        android:text="使用JSON解析"
        android:textSize="30sp"/>
    
    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:<strong>gravity</strong>="center">
        
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="账号"
        android:textSize="20sp"
        android:layout_marginRight="20dp" />
        
        <EditText 
            android:id="@+id/et_id"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
    
	<LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:<strong>gravity</strong>="center">
        
        <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="密码"
        android:textSize="20sp"
        android:layout_marginRight="20dp" />
        
        <EditText 
            android:id="@+id/et_psw"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>    
    
	<Button 
	    android:id="@+id/btn_login"
	    android:layout_width="match_parent"
	    android:layout_height="wrap_content"
	    android:text="登录"/>
</LinearLayout>
로그인 후 복사
MainActivity.java

package com.example.jsontest;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.<strong>Apache</strong>.http.HttpEntity;
import org.<strong>Apache</strong>.http.HttpResponse;
import org.<strong>Apache</strong>.http.NameValuePair;
import org.<strong>Apache</strong>.http.client.HttpClient;
import org.<strong>Apache</strong>.http.client.entity.UrlEncodedFormEntity;
import org.<strong>Apache</strong>.http.client.methods.HttpPost;
import org.<strong>Apache</strong>.http.impl.client.DefaultHttpClient;
import org.<strong>Apache</strong>.http.message.BasicNameValuePair;
import org.<strong>Apache</strong>.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Looper;
import android.support.v7.app.ActionBar<strong>Activity</strong>;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class Main<strong>Activity</strong> extends ActionBar<strong>Activity</strong> {
	EditText et_id;
	EditText et_psw;
	Button btn_login;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.<strong>Activity</strong>_main);
        
        initView();
    }
    
    private boolean check(String id, String psw) {
    	if("".equals(id) || "".equals(psw))
    		return false;
    	return true;
    }
    
    private void initView() {
    	et_id = (EditText)findViewById(R.id.et_id);
    	et_psw = (EditText)findViewById(R.id.et_psw);
    	btn_login = (Button)findViewById(R.id.btn_login);
    	
    	btn_login.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//获取用户输入的用户名和密码
				final String id = et_id.getText().toString().trim();
				final String psw = et_psw.getText().toString().trim();
				
				if(check(id, psw)) {
					new Thread() {
						public void run() {
							try {
								HttpPost post = new HttpPost("这里要改成服务器文件所在URL地址");
								//如果传递参数个数比较多,可以对传递的参数进行封装
								List<NameValuePair> params = new ArrayList<NameValuePair>();
								params.add(new BasicNameValuePair("id", id));
								params.add(new BasicNameValuePair("psw", psw));
								//设置请求参数
								post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
								
								HttpClient httpClient = new DefaultHttpClient();
								//发送POST请求
								HttpResponse response = httpClient.execute(post);
								//如果服务器成功地返回响应
								if(response.getStatusLine().getStatusCode() == 200) {
									//String msg = EntityUtils.toString(response.getEntity());
									HttpEntity entity = response.getEntity();
									InputStream is = entity.getContent();
									
									BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
									StringBuilder sb = new StringBuilder();
									sb.append(reader.readLine() + "\n"); // 这里 “ + "\n" ”加不加似乎对结果没有什么影响
									
									String line = "0";
									while((line = reader.readLine()) != null) {
										sb.append(line + "\n"); // 这里 “ + "\n" ”加不加似乎对结果没有什么影响
									}
									is.close();
									
									//获取请求响应结果
									String result = sb.toString();
									System.out.println(result);
									
									//打包成JSON进行解析
									JSONArray jsonArray = new JSONArray(result);
									JSONObject jsonData = null;
									//返回用户ID,用户密码
									String userId = "";
									String userPsw = "";
									//使用List进行存储
									List<String> data = new ArrayList<String>();
									for(int i = 0; i < jsonArray.length(); i++) {
										jsonData = jsonArray.getJSONObject(i);
										userId = jsonData.getString("userId"); //userId是来源于服务器端php程序响应结果res的<strong>索引</strong>,根据<strong>索引</strong>获取值
										userPsw = jsonData.getString("userPsw"); //userPsw是来源于服务器端php程序响应结果res的<strong>索引</strong>,根据<strong>索引</strong>获取值
										data.add("用户ID:" + userId + ",用户密码:" + userPsw); //保存返回的值,可进行相应的操作,这里只进行显示
									}
									
									Looper.prepare();
									Toast.makeText(Main<strong>Activity</strong>.this, data.toString(), Toast.LENGTH_LONG).show();
									Looper.loop();
								}
								else {
									Looper.prepare();
									Toast.makeText(Main<strong>Activity</strong>.this, "登录失败", Toast.LENGTH_LONG).show();
									Looper.loop();
								}
							}
							catch(<strong>Exception</strong> e) {
								e.printStackTrace();
							}
						}
					}.start();
				}
			}
		});
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent <strong>Activity</strong> in <strong>AndroidManifest.xml</strong>.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
로그인 후 복사

다음은 서버측 PHP 파일입니다(해당 파일은 데이터베이스에 연결 작업을 원하는 경우 데이터베이스에 연결하여 동적 데이터를 얻을 수 있습니다. PHP를 아는 사람은 쉽게 데이터베이스에 연결하는 작업으로 변경할 수 있습니다. 🎜> 데이터 획득)

checkId.php

<?php
	//获取客户端发送过来的ID和密码
	$id=$_POST[&#39;id&#39;];
	$psw=$_POST[&#39;psw&#39;];

	if($id == "admin" && $psw == "123") {
		$res=array(array());
		$res[0][&#39;userId&#39;]=$id;
		$res[0][&#39;userPsw&#39;]=$psw;

		$res[1][&#39;userId&#39;]="testId1";
		$res[1][&#39;userPsw&#39;]="testPsw1";

		$res[2][&#39;userId&#39;]="testId2";
		$res[2][&#39;userPsw&#39;]="testPsw2";
	}

	echo json_encode($res);
?>
로그인 후 복사


위 내용은 Android PHP가 HttpClient를 사용하여 POST 요청을 제출하고 JSON을 사용하여 중력, Apache, 예외, 인덱스 및 데이터베이스 연결을 포함한 응답을 구문 분석하는 방법을 소개합니다. PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 채팅 명령 및 사용 방법
4 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

새로운 보고서는 소문난 삼성 갤럭시 S25, 갤럭시 S25 플러스, 갤럭시 S25 울트라 카메라 업그레이드에 대한 비판적인 평가를 제공합니다. 새로운 보고서는 소문난 삼성 갤럭시 S25, 갤럭시 S25 플러스, 갤럭시 S25 울트라 카메라 업그레이드에 대한 비판적인 평가를 제공합니다. Sep 12, 2024 pm 12:23 PM

최근 아이스 유니버스는 삼성의 차기 플래그십 스마트폰으로 널리 알려진 갤럭시 S25 울트라에 대한 세부 정보를 꾸준히 공개해 왔습니다. 무엇보다도 유출자는 삼성이 카메라 업그레이드를 하나만 가져올 계획이라고 주장했습니다.

삼성 갤럭시 S25 울트라, 디자인 변경 루머가 공개된 첫 번째 렌더링 이미지 유출 삼성 갤럭시 S25 울트라, 디자인 변경 루머가 공개된 첫 번째 렌더링 이미지 유출 Sep 11, 2024 am 06:37 AM

OnLeaks는 이제 Android Headlines와 제휴하여 X(이전 Twitter) 팔로어로부터 4,000달러 이상의 수익을 창출하려는 시도가 실패한 지 며칠 후 Galaxy S25 Ultra에 대한 첫 번째 모습을 제공합니다. 맥락에 따라 h 아래에 포함된 렌더링 이미지

IFA 2024 | TCL의 NXTPAPER 14는 성능 면에서는 Galaxy Tab S10 Ultra와 일치하지 않지만 크기에서는 거의 일치합니다. IFA 2024 | TCL의 NXTPAPER 14는 성능 면에서는 Galaxy Tab S10 Ultra와 일치하지 않지만 크기에서는 거의 일치합니다. Sep 07, 2024 am 06:35 AM

TCL은 두 가지 새로운 스마트폰을 발표하는 것과 함께 NXTPAPER 14라는 새로운 Android 태블릿도 발표했는데, TCL의 거대한 화면 크기는 판매 포인트 중 하나입니다. NXTPAPER 14는 TCL의 시그니처 브랜드인 무광택 LCD 패널 버전 3.0을 갖추고 있습니다.

Vivo Y300 Pro는 7.69mm의 슬림한 본체에 6,500mAh 배터리를 탑재했습니다. Vivo Y300 Pro는 7.69mm의 슬림한 본체에 6,500mAh 배터리를 탑재했습니다. Sep 07, 2024 am 06:39 AM

Vivo Y300 Pro는 방금 완전히 공개되었으며 대용량 배터리를 갖춘 가장 얇은 중급 Android 휴대폰 중 하나입니다. 정확히 말하면 스마트폰의 두께는 7.69mm에 불과하지만 배터리 용량은 6,500mAh입니다. 최근 출시된 것과 동일한 용량이다.

Samsung Galaxy S24 FE는 4가지 색상과 2가지 메모리 옵션으로 예상보다 낮은 가격으로 출시될 예정 Samsung Galaxy S24 FE는 4가지 색상과 2가지 메모리 옵션으로 예상보다 낮은 가격으로 출시될 예정 Sep 12, 2024 pm 09:21 PM

삼성전자는 팬에디션(FE) 스마트폰 시리즈를 언제 업데이트할지 아직 힌트를 주지 않았다. 현재 상태로 Galaxy S23 FE는 2023년 10월 초에 출시된 회사의 최신 버전으로 남아 있습니다.

새로운 보고서는 소문난 삼성 갤럭시 S25, 갤럭시 S25 플러스, 갤럭시 S25 울트라 카메라 업그레이드에 대한 비판적인 평가를 제공합니다. 새로운 보고서는 소문난 삼성 갤럭시 S25, 갤럭시 S25 플러스, 갤럭시 S25 울트라 카메라 업그레이드에 대한 비판적인 평가를 제공합니다. Sep 12, 2024 pm 12:22 PM

최근 아이스 유니버스는 삼성의 차기 플래그십 스마트폰으로 널리 알려진 갤럭시 S25 울트라에 대한 세부 정보를 꾸준히 공개해 왔습니다. 무엇보다도 유출자는 삼성이 카메라 업그레이드를 하나만 가져올 계획이라고 주장했습니다.

Xiaomi Redmi Note 14 Pro Plus는 Light Hunter 800 카메라를 탑재한 최초의 Qualcomm Snapdragon 7s Gen 3 스마트폰으로 출시됩니다. Xiaomi Redmi Note 14 Pro Plus는 Light Hunter 800 카메라를 탑재한 최초의 Qualcomm Snapdragon 7s Gen 3 스마트폰으로 출시됩니다. Sep 27, 2024 am 06:23 AM

Redmi Note 14 Pro Plus는 이제 작년 Redmi Note 13 Pro Plus(Amazon에서 현재 $375)의 직접적인 후속 제품으로 공식화되었습니다. 예상대로 Redmi Note 14 Pro Plus는 Redmi Note 14 및 Redmi Note 14 Pro와 함께 Redmi Note 14 시리즈를 주도합니다. 리

iQOO Z9 Turbo Plus: 잠재적으로 강화된 시리즈 플래그십에 대한 예약 시작 iQOO Z9 Turbo Plus: 잠재적으로 강화된 시리즈 플래그십에 대한 예약 시작 Sep 10, 2024 am 06:45 AM

OnePlus의 자매 브랜드 iQOO는 2023-4년 제품 주기가 거의 끝날 수 있습니다. 그럼에도 불구하고 브랜드는 Z9 시리즈가 아직 끝나지 않았다고 선언했습니다. 최종이자 아마도 최고급인 Turbo+ 변형이 예상대로 발표되었습니다. 티

See all articles