Volley框架如何 post xml

首先看效果图


第一步需要自定义XMLRequest,代码如下:

import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;


import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;


import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;


public class XMLRequest extends Request<XmlPullParser> {
/** Charset for request. */
    private static final String PROTOCOL_CHARSET = "utf-8";


    /** Content type for request. */
    private static final String PROTOCOL_CONTENT_TYPE =
        String.format("text/xml; charset=%s", PROTOCOL_CHARSET);
    private final String mRequestBody;
private final Listener<XmlPullParser> mListener;


public XMLRequest(int method, String url,String requestBody, Listener<XmlPullParser> listener,
ErrorListener errorListener) {
super(method, url, errorListener);
mListener = listener;
mRequestBody=requestBody;
}


public XMLRequest(String url,String requestBody, Listener<XmlPullParser> listener,
ErrorListener errorListener) {
this(Method.POST, url,requestBody, listener, errorListener);

}




@Override
protected Response<XmlPullParser> parseNetworkResponse(
NetworkResponse response) {
try {
String xmlString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser = factory.newPullParser();
xmlPullParser.setInput(new StringReader(xmlString));
return Response.success(xmlPullParser,
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (XmlPullParserException e) {
return Response.error(new ParseError(e));
}
}


@Override
protected void deliverResponse(XmlPullParser response) {
mListener.onResponse(response);
}
/**
    * @deprecated Use {@link #getBodyContentType()}.
    */
   @Override
   public String getPostBodyContentType() {
       return getBodyContentType();
   }


   /**
    * @deprecated Use {@link #getBody()}.
    */
   @Override
   public byte[] getPostBody() {
       return getBody();
   }
@Override
    public String getBodyContentType() {
        return PROTOCOL_CONTENT_TYPE;
    }


    @Override
    public byte[] getBody() {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes(PROTOCOL_CHARSET);
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                    mRequestBody, PROTOCOL_CHARSET);
            return null;
        }
    }
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = new HashMap<String, String>();  
    headers.put("Charset", "UTF-8");  
    headers.put("Content-Type", "text/xml");  
    headers.put("Accept-Encoding", "*/*"); 
    headers.put("Connection", "close");
    return headers;
    }
}

然后可以使用了,使用方法跟普通的request一样,代码如下:

public class LifeFragment extends BaseFragment {
public static final String BUNDLE_USERT = "UserName";
private String mUsrNam;
private GridView mGridView;
private List<PhotoInfo> mGridList ;
private int section = 1;
private Map<String, Integer> sectionMap = new HashMap<String, Integer>();
private MyBaseAdapter mAdapter;
private ProgressBar mPb;
private LinearLayout mLayEdit;
private Button mBtnEdit;
private Button mBtnCancle;
String mGetPhotoListBody = "<GetPhotoListRequest xmlns=\"http://ws.wellav.com/hiapi/20150925\">"
+ "<Token>28213306:CNUuDvlHKbzlNZ6rvXwR50L+E3R0KA5BRbVKkAA36aVlVaFfYRGwDGDkaTNnccB6hlIDDF+/qXeqkr/qqKocFw==</Token>"
+ "<FamilyID>1</FamilyID>" + "</GetPhotoListRequest>";
private Handler mHandler;


@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(msg.obj!=null){
mGridList=XMLPhotosParser.ParseXMLPhotos((XmlPullParser)msg.obj);
Collections.sort(mGridList, new Comparator<PhotoInfo>() {
@Override
public int compare(PhotoInfo o1, PhotoInfo o2) {
return o1.getmTime().compareTo(o2.getmTime());
}
});

for(ListIterator<PhotoInfo> it = mGridList.listIterator(); it.hasNext();){
PhotoInfo mGridItem = it.next();
String ym = mGridItem.getmTime().substring(0, 10);
if(!sectionMap.containsKey(ym)){
mGridItem.setmSection(section);
sectionMap.put(ym, section);
section ++;
}else{
mGridItem.setmSection(sectionMap.get(ym));
}
}
mAdapter = new LifeAdapter(getActivity(), mGridList);
mGridView.setAdapter(mAdapter);
}
mPb.setVisibility(View.INVISIBLE);
// Log.e("", "size="+mGridList.size());
}
};
super.onCreate(savedInstanceState);
}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {


View view = inflater.inflate(R.layout.frag_life, null);
Bundle arguments = getArguments();
if (arguments != null) {
mUsrNam = arguments.getString(BUNDLE_USERT);
}


mGridView = (GridView) view
.findViewById(R.id.lifeFrag_gridId);
mPb=(ProgressBar)view.findViewById(R.id.lifeFrag_pbId);
mLayEdit = (LinearLayout) view.findViewById(R.id.lifeFrag_layEditId);
mBtnEdit = (Button) view.findViewById(R.id.lifeFrag_btnEditId);
mBtnCancle = (Button) view.findViewById(R.id.lifeFrag_btnCancleId);
mBtnEdit.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mLayEdit.setVisibility(View.VISIBLE);
mBtnEdit.setVisibility(View.INVISIBLE);
mAdapter.setmIsEditMode(true);
mAdapter.notifyDataSetChanged();
}
});
mBtnCancle.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mLayEdit.setVisibility(View.INVISIBLE);
mBtnEdit.setVisibility(View.VISIBLE);
mAdapter.setmIsEditMode(false);
mAdapter.notifyDataSetChanged();
}
});

isViewCreated=true;
lazyLoad();
return view;
}


public static LifeFragment newInstance(String usrNam) {


Bundle bundle = new Bundle();
bundle.putString(BUNDLE_USERT, usrNam);
LifeFragment fragment = new LifeFragment();
fragment.setArguments(bundle);
return fragment;
}


@Override
public MyBaseAdapter getmBaseAdapter() {
// TODO Auto-generated method stub
return null;
}


@Override
protected void lazyLoad() {
// TODO Auto-generated method stub
if (!isViewCreated || !isVisible || mPb.getVisibility()==View.INVISIBLE) {  
            return;  
        }
XMLRequest xmlRequest = new XMLRequest(
"http://10.100.0.94:9090/services/hiapi/GetPhotoList",
mGetPhotoListBody, new Response.Listener<XmlPullParser>() {


@Override
public void onResponse(XmlPullParser response) {
// TODO Auto-generated method stub
Log.e("", "response");
Message msg=mHandler.obtainMessage();
msg.what=0;
msg.obj=response;
mHandler.sendMessage(msg);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
Message msg=mHandler.obtainMessage();
msg.what=0;
msg.obj=null;
mHandler.sendMessage(msg);
}
});


VolleyRequestQueueManager.addRequest(xmlRequest, null);
}


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

无v邪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值